import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MessageService {

  private subject_array = new Map<string , Subject<any>>()

  private state: State

  constructor() {
    this.state = new State()
  }

  boot(name: string) {
    if (name === '' || this.subject_array.has(name)) {
      return null;
    }
    this.subject_array.set(name, new Subject<any>());
  }

  send(name: string, val: any) {
    if (name === '') {
      return null;
    }
    this.subject_array.get(name).next(val);
  }

  clear(name: string) {
    if (name === '') {
      return null;
    }
    this.subject_array.set(name, new Subject<any>());
    // this.subject_array.get(name).next();
  }

  receive(name: string): Observable<any> {
    if (name === '') {
      return null;
    }
    if (this.subject_array.get(name) !== undefined) {
      return this.subject_array.get(name).asObservable();
    }

  }

  exist(name: string): boolean {
    if (name === '') {
      return null;
    }
    return this.subject_array.has(name);
  }

  initState() {
    this.state.admin = null
  }

  public setState(name: string, value: string) {
    this.state[name] = value
  }

  public getState(name: string) {
    return this.state[name]
  }

}

class State {

  private _admin: any

  private _code: any

  public get admin() {
    return this._admin;
  }

  public set admin(name: any) {
      this._admin = name;
  }

  public get code() {
    return this._code;
  }

  public set code(name: any) {
    this._code = name
  }

  constructor() {}
}
